package com.back.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.back.config.AliPayConfig;
import com.back.service.PayService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class AliPayServiceImpl implements PayService {


    @Resource
    private AliPayConfig aliPayConfig;


    @Override
    public String pay() {

        AlipayClient alipayClient = new DefaultAlipayClient(
                aliPayConfig.getGatewayUrl(),
                aliPayConfig.getAppId(),
                aliPayConfig.getMerchantPrivateKey(),
                "json", aliPayConfig.getCharset(),
                aliPayConfig.getAlipayPublicKey(),
                aliPayConfig.getSignType());

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // alipayRequest.setReturnUrl(AlipayConfig.return_url);
        // alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ "00002" +"\","
                + "\"total_amount\":\""+ 120000.00 +"\","
                + "\"subject\":\""+ "显卡" +"\","
                + "\"body\":\""+ "测试" +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
            return result;
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    public String query() {
        AlipayClient alipayClient = new DefaultAlipayClient(
                aliPayConfig.getGatewayUrl(),
                aliPayConfig.getAppId(),
                aliPayConfig.getMerchantPrivateKey(),
                "json", aliPayConfig.getCharset(),
                aliPayConfig.getAlipayPublicKey(),
                aliPayConfig.getSignType());


        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ "00002" +"\"}");
        String result = null;
        //请求
        try {
             result = alipayClient.execute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        return result;
    }


    @Override
    public Integer getType() {
        return 1;
    }
}
